<template>
  <div class="leftNav">
    <el-scrollbar view-style="height:100%">
      <el-menu
        class="el-menu-vertical"
        @select="selectMenu"
        :default-active="defaultActive"
      >
        <MenuItem
          v-for="(item, index) in renderRoutes"
          ref="MenuItem"
          :route="item"
          :key="index"
        />
      </el-menu>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRaw } from "vue";
import store from "@/store";
import MenuItem from "./menuItem.vue";
import { RouteRecordRaw } from "vue-router";
import router from "@/router";
export default defineComponent({
  components: { MenuItem },
  setup(prop, context) {
    const defaultActive = ref<string>("");
    return {
      defaultActive,
    };
  },
  computed: {
    // 渲染的路由树
    renderRoutes(): Array<object> {
      return store.state.renderRouterTree;
    },
    // 所有路由
    routes(): Array<RouteRecordRaw> {
      return store.state.routes;
    },
    // 菜单路由扁平化
    routesToArray(): Array<object> {
      const renderRouterTree: Array<object> = store.state.renderRouterTree;
      const ar: Array<object> = [];
      const p: Function = (arr: Array<any>) => {
        arr.forEach((item) => {
          if (item.component) {
            ar.push({
              ...item,
              children: [],
            });
          }
          if (item.children && item.children.length) {
            p(item.children);
          }
        });
      };
      p(renderRouterTree);
      return ar;
    },
  },
  methods: {
    selectMenu(index: string, indexPath: Array<string>): void {
      const routePath: string = "/" + index;
      const findRoute: any = this.routes.find(
        (item: any) => item.path === routePath
      );
      findRoute ? this.$router.push({ path: routePath }) : null;
    },
  },
  mounted() {
    const findRoute:any = this.routesToArray.find((item:any)=>item.meta.path === this.$route.meta.path);
    this.defaultActive = findRoute.meta.path;
  },
});
</script>
<style scoped lang="scss">
.leftNav {
  height: 100%;
  .el-menu-vertical {
    min-height: 100%;
  }
}
</style>